/**
 *	计算业务机会上一阶段的赢单率
 *	created by Harry
 */
public class PrivorWinRatioHandler implements Triggers.handler{
	public void handle(){
		List<Opportunity> oppList = (List<Opportunity>) Trigger.new;
		Map<Id,Opportunity> oldOppMap = (Map<Id,Opportunity>) Trigger.oldMap;
		
        
       Map<Id,Opportunity> changedOppList = new Map<Id,Opportunity>();
       List<Opportunity> updateList = new List<Opportunity>();
		for(Opportunity opp : oppList ){
			Opportunity oldOpp = oldOppMap.get(opp.Id);
			if(!opp.StageName.equals(oldOpp.StageName)){//阶段变更
                changedOppList.put(oldOpp.Id,oldOpp);
                updateList.add(opp);
			                
			}
		}
        
        if(changedOppList.keySet().size() > 0){
        	Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>(
			[SELECT Id,StageName,StageCanChange__c,WinRatio__c,
				(SELECT Id, Name, Opportunity__c, WinRadioSum__c FROM OpportunityStage__r)
			FROM Opportunity 
			WHERE Id IN: changedOppList.keySet()]);
            
        	for(Opportunity opp :updateList){
                
            	Opportunity opportunity = oppMap.get(opp.Id);
                Opportunity oldOpp = changedOppList.get(opp.Id);
				List<StageWinRate__c> swrList = opportunity.OpportunityStage__r;
                for(StageWinRate__c swr: swrList){
                    if(oldOpp.StageName==swr.Name){//取上一阶段
                        opp.PriorWinRatio__c = swr.WinRadioSum__c;
                    }
                }
            
            }
        }
	}
}